/** home page script start */

function makeColorOnrow(id) {
	var rowCount = $('#' + id + ' tr').length;
	$("#" + id + " tr").find('td:last').each(function() {
		var title = $(this).attr("title");
		if (title == "color-red") {
			// alert('red');
			$(this).parent().addClass("sma_redcolor");
		}
		if (title == "color-green") {
			$(this).parent().addClass("sma_greencolor");
		}

	});

}

/** screener page script start */

function comapanySearch() {
	$("#btn_search_allSearch").on("click", function() {
		console.info("search");
		searchData("filterForm_allSearch");
	});

	$("#resetFilter_allSearch").on("click", function() {
		console.info("reset filter");
		$("#filterForm_allSearch")[0].reset();
		searchData("filterForm_allSearch");
	});
}

function updateCharts(paging, containerId, currentPageId, type, timeRange,
		showVolume, code, name) {
	if (showVolume == null) {
		showVolume = true;
	}
	var currentPage = $("#" + currentPageId).val();
	var param = "page=" + currentPage;

	if (code != null && code != '') {
		param += "&code=" + code;
	}
	if (name != null && name != '') {
		param += "&name=" + name;
	}

	var url = "/StockScreener/charts/comData?" + param;
	$.ajax({
		url : url,
		type : "GET",
		contentType : "application/json; charset=utf-8",
		data : {},
		dataType : "json",
		success : function(data, st) {
			if (st == "success") {
				console.info("data :" + data);
				createCharts(data, paging, containerId, type, timeRange,
						showVolume);
			}
		},
		error : function() {
			alert("Error with AJAX callback");
		}
	});
}

function updateChartPageCharts(paging, containerId, currentPageId, type,
		timeRange, showVolume, code, name) {
	if (showVolume == null) {
		showVolume = true;
	}

	var currentPage = $("#" + currentPageId).val();

	var param;

	if (name != null && name != '') {
		"page=" + currentPage;
	} else {
		"page=" + 1;
	}
	if (code != null && code != '') {
		param += "&code=" + code;
	}
	if (name != null && name != '') {
		param += "&name=" + name;
	}

	var url = "/StockScreener/chart/main.html";
	doAjax(url, param, moduleLoadCallBack, containerId, "html", "POST");

	var url = "/StockScreener/charts/comData?" + param;
	$.ajax({
		url : url,
		type : "GET",
		contentType : "application/json; charset=utf-8",
		data : {},
		dataType : "json",
		success : function(data, st) {
			if (st == "success") {
				console.info("data :" + data);
				createCharts(data, paging, containerId, type, timeRange,
						showVolume);
			}
		},
		error : function() {
			alert("Error with AJAX callback");
		}
	});

}

function createCharts(data, paging, containerId, chartType, timeRange,
		showVolume) {
	console.info('createPaging :' + paging + ' containerId :' + containerId);

	Highcharts.setOptions({
		global : {
			timezoneOffset : ((-5.50) * 60)
		}
	});

	if (chartType == null) {
		chartType = 'line';
	}
	if (timeRange == null) {
		timeRange = 'daily';
	}

	$.each(data, function(index, value) {
		$.getJSON(
				('/StockScreener/charts/list?code=' + value + '&type='
						+ chartType + '&timeRange=' + timeRange
						+ "&showVolume=" + showVolume), function(data) {
					// Create the chart
					var element = $('#' + containerId + '_' + value);
					var companyCode = value.substr(0, value.length - 5) + "."
							+ value.substr(value.length - 5, value.length - 1);

					if (timeRange == "intraday") {
						element.highcharts('StockChart', {
							rangeSelector : {
								selected : 1,
								inputEnabled : element.width() > 480
							},

							title : {
								text : companyCode
							},

							rangeSelector : {
								buttons : [ {
									type : 'hour',
									count : 1,
									text : '1h'
								}, {
									type : 'day',
									count : 1,
									text : '1D'
								}, {
									type : 'all',
									count : 1,
									text : 'All'
								} ],
								selected : 1,
								inputEnabled : false
							},

							series : [ {
								name : companyCode,
								type : chartType,
								data : data,
								tooltip : {
									valueDecimals : 2
								}
							} ]
						});
					} else {
						if (showVolume) {
							createChartWithVolume(data, element, chartType);
						} else {
							createChartWithoutVolume(data, element, chartType);
						}
					}
				});
	});
	if (paging) {
		createPaging("/StockScreener/chart/main.html", "contentDiv");
		addChartTypeControllers();
	}
}

function createChartWithoutVolume(data, element, chartType) {
	element.highcharts('StockChart', {
		rangeSelector : {
			selected : 1,
			inputEnabled : element.width() > 480
		},

		title : {
			text : companyCode
		},

		series : [ {
			name : companyCode,
			type : chartType,
			data : data,
			tooltip : {
				valueDecimals : 2
			}
		} ]
	});

}

function createChartWithVolume(data, element, chartType) {

	var ohlc = [], volume = [], dataLength = data.length, i = 0;
	for (i; i < dataLength; i += 1) {
		if (chartType == 'candlestick') {
			ohlc.push([ data[i][0], // the date
			data[i][1], // open
			data[i][2], // high
			data[i][3], // low
			data[i][4] // close
			]);

			volume.push([ data[i][0], // the date
			data[i][5] // the volume
			]);
		} else {
			ohlc.push([ data[i][0], // the date
			data[i][1], // open
			]);

			volume.push([ data[i][0], // the date
			data[i][2] // the volume
			]);
		}
	}
	// create the chart
	element.highcharts('StockChart', {

		rangeSelector : {
			inputEnabled : element.width() > 480,
			selected : 1
		},

		yAxis : [ {
			labels : {
				align : 'right',
				x : -3
			},
			title : {
				text : 'OHLC'
			},
			height : '60%',
			lineWidth : 2
		}, {
			labels : {
				align : 'right',
				x : -3
			},
			title : {
				text : 'Volume'
			},
			top : '65%',
			height : '35%',
			offset : 0,
			lineWidth : 2
		} ],

		series : [ {
			type : chartType,
			name : 'AAPL',
			data : ohlc
		}, {
			type : 'column',
			name : 'Volume',
			data : volume,
			yAxis : 1
		} ]
	});
}

function addChartTypeControllers() {
	$("#candleChart").unbind("click");
	$("#candleChart").click(
			function() {
				var code = $("#ticker").val();
				var name = $("#companyName").val();

				if (code == null && code == '') {
					code = null;
				}
				if (name == null && name == '') {
					name = null;
				}

				updateCharts(true, 'container', 'currentPage', 'candlestick',
						null, null, code, name);
				// updateCharts(true, 'container', 'currentPage',
				// 'candlestick');
			});

	$("#lineChart").unbind("click");
	$("#lineChart").click(
			function() {

				var code = $("#ticker").val();
				var name = $("#companyName").val();

				if (code == null && code == '') {
					code = null;
				}
				if (name == null && name == '') {
					name = null;
				}

				updateCharts(true, 'container', 'currentPage', 'line', null,
						null, code, name);
				// updateCharts(true, 'container', 'currentPage', 'line');
			});

	$("#dailyChart").unbind("click");
	$("#dailyChart").click(
			function() {
				var code = $("#ticker").val();
				var name = $("#companyName").val();

				if (code == null && code == '') {
					code = null;
				}
				if (name == null && name == '') {
					name = null;
				}

				updateCharts(true, 'container', 'currentPage', 'line', 'daily',
						null, code, name);

				// updateCharts(true, 'container', 'currentPage',
				// 'line','daily');
			});

	$("#weeklyChart").unbind("click");
	$("#weeklyChart").click(
			function() {
				var code = $("#ticker").val();
				var name = $("#companyName").val();

				if (code == null && code == '') {
					code = null;
				}
				if (name == null && name == '') {
					name = null;
				}

				updateCharts(true, 'container', 'currentPage', 'line',
						'weekly', null, code, name);

				// updateCharts(true, 'container', 'currentPage',
				// 'line','weekly');
			});

	$("#monthlyChart").unbind("click");
	$("#monthlyChart").click(
			function() {
				var code = $("#ticker").val();
				var name = $("#companyName").val();

				if (code == null && code == '') {
					code = null;
				}
				if (name == null && name == '') {
					name = null;
				}

				updateCharts(true, 'container', 'currentPage', 'line',
						'monthly', null, code, name);

				// updateCharts(true, 'container', 'currentPage', 'line',
				// 'monthly');
			});

	$("#intradayChart").unbind("click");
	$("#intradayChart").click(
			function() {
				var code = $("#ticker").val();
				var name = $("#companyName").val();

				if (code == null && code == '') {
					code = null;
				}
				if (name == null && name == '') {
					name = null;
				}

				updateCharts(true, 'container', 'currentPage', 'line',
						'intraday', null, code, name);

				// updateCharts(true, 'container', 'currentPage', 'line',
				// 'intraday');
			});

	$("#yearlyChart").unbind("click");
	$("#yearlyChart").click(
			function() {
				var code = $("#ticker").val();
				var name = $("#companyName").val();

				if (code == null && code == '') {
					code = null;
				}
				if (name == null && name == '') {
					name = null;
				}

				updateCharts(true, 'container', 'currentPage', 'line',
						'yearly', null, code, name);

				// updateCharts(true, 'container', 'currentPage', 'line',
				// 'yearly');
			});

}

function createPaging(url, containerDivId) {
	console.info('calling createPaging ' + url);
	if (url == null) {
		url = "/StockScreener/chart/main.html";
	}
	$("#showNext").unbind("click");
	$("#showNext").click(
			function() {
				var page = $(this).attr("lang");

				doAjax(url, "page=" + page, moduleLoadCallBack, containerDivId,
						"html", "POST");
			});

	$("#showPrev").unbind("click");
	$("#showPrev").click(
			function() {
				var page = $(this).attr("lang");

				doAjax(url, "page=" + page, moduleLoadCallBack, containerDivId,
						"html", "POST");
			});

	$("a[id*='pageNum']").unbind("click");
	$("a[id*='pageNum']").click(
			function() {
				var page = $(this).attr("lang");

				doAjax(url, "page=" + page, moduleLoadCallBack, containerDivId,
						"html", "POST");
			});

}

function moduleLoadCallBack(data, divId) {
	replaceExisiting(data, divId);
	// updateCharts();
}

function updateGrids(dataUrl, listUrl, gridId, pagerId) {
	var colNames, colModel;
	$.ajax({
		url : dataUrl,
		type : "GET",
		contentType : "application/json; charset=utf-8",
		data : {},
		dataType : "json",
		success : function(data, st) {
			if (st == "success") {
				colNames = data.colNames;// jqgrid heading data
				colModel = data.colModel; // its column model
				createGrid(listUrl, gridId, pagerId);
			}
		},
		error : function() {
			alert("Error with AJAX callback");
		}
	});

	function createGrid(listUrl, gridId, pagerId) {
		$("#" + gridId).jqGrid({
			url : listUrl,
			datatype : "json",
			mtype : 'POST',
			height : 300,
			autowidth : true,
			viewrecords : true,
			colNames : colNames,
			colModel : colModel,
			jsonReader : {
				root : "data",
				page : "page",
				total : "total",
				records : "records"
			},
			gridComplete : function() {
				var smaId = gridId.substring(0, 3);
				if (smaId == 'sma') {
					makeColorOnrow(gridId);
				}

			},
			pager : pagerId,
			rowNum : 10,
			rownumbers : true

		});
	}
}

function searchData(formId) {

	var gridId = $("div:visible[id*=gbox_]").attr("id");
	var snShotDiv = $("div:visible[id*=snContentDiv]").attr("id");

	if (gridId != null) {
		var gridName = gridId.replace("gbox_", "");
		var postData = $("#" + gridName).jqGrid('getGridParam', 'postData');
		result = parseArray($("#" + formId).serializeArray());

		jQuery.extend(postData, result);

		// add aditional param as search
		jQuery.extend(postData, {
			search : "yes"
		});

		$("#" + gridName).setGridParam({
			postData : postData,
			datatype : 'json'
		});
		$("#" + gridName).jqGrid().trigger("reloadGrid");
	} else if (snShotDiv != null) {
		var code = $("#ticker").val();
		var name = $("#companyName").val();
		var url = "/StockScreener/snapshot/list";

		if (code == null || code == '') {
			code = null;
		}
		if (name == null || name == '') {
			name = null
		}

		$.ajax({
			url : url,
			type : "POST",
			data : {
				name : name,
				code : code,
				page : 1
			},
			success : function(data) {
				replaceExisiting(data, snShotDiv);
			}

		});

	} else {
		var code = $("#ticker").val();
		var name = $("#companyName").val();

		updateChartPageCharts(false, 'contentDiv', 'currentPage', 'line',
				'intraday', true, code, name);
	}

}

function resetFilters(formId) {
	console.info("Reset method called " + formId + " "
			+ $("#" + formId).attr("action"));
	$("#" + formId)[0].reset();

	// then do a search again
	searchData(formId);
}

function isEmpty(str) {
	return (!str || 0 === str.length);
}

function setSearchForAllTabs() {
	var companySearch = $("div:visible[id*=com_search_div]").find('form').attr("id");

	var filterSearch = $("div:visible[id*=criteriaTabs]").find('form').attr("id");

	if (companySearch != null && companySearch != '') {
		searchData(companySearch);
	}
	if (filterSearch != null && filterSearch != '') {
		searchData(filterSearch);
	}
}

/** screener page script end */

